<?php

namespace Common\Controller;

use Think\Controller;

/**
 * 公共的控制器
 *
 * Class CommonController
 */
class CommonController extends Controller
{
    const SUCCESS_CODE = 100; // 操作成功
    const ERROR_CODE   = 101; // 操作失败
    const SUCCESS_MSG  = 'success';         // 操作成功
    const ERROR_MSG    = 'error';           // 操作失败
    const PARAM_ERROR  = 'parameter error'; // 参数错误
    const DENY_MSG     = 'access_deny';     // 操作失败
    const DATA_EMPTY   = 'empty';           // 没有数据
    const TIME_OUT     = 30;                // 操作超时
    const PER_PAGE_NUMBER = 10;             // 每页10条

    // API信息
    const CODE_REGISTER_TYPE = 1;        // 注册验证码类型
    const CODE_GETPASS_TYPE  = 2;        // 找回密码验码类型
    const CODE_REGISTER_SEND_TIMES = 5 ; // 注册验证码发送次数

    // 会员冻结金币
    const FREEZE_COIN = 999;
    /**
     * 返回数据
     *
     * @param array $data
     * @param int $code
     * @param string $message
     */
    protected function showMessage($data = array(), $code = self::SUCCESS_CODE, $message = self::SUCCESS_MSG)
    {
        $return = array(
            'code'    => $code,
            'data'    => $data,
            'message' => $message,
        );
        $this->ajaxReturn($return, 'json');
    }

    /**
     * 验证会员有效性
     *
     * @param $id
     * @return bool|mixed
     */
    protected function checkMemberAvailable($id)
    {
        $where = array('id' => $id,);
        $data = M('member')->where($where)->find();
        if ($data) {
            return $data;
        } else {
            return false;
        }
    }

    /**
     * 验证比赛的有效性
     *
     * @param $match_id
     * @return bool|mixed
     */
    protected function checkMatchAvailable($match_id)
    {
        $where = array('id' => $match_id);
        $data = M('match')->where($where)->find();
        if ($data) {
            return $data;
        } else {
            return false;
        }
    }

    /**
     * 获取种子选手的投票
     *
     * @param $match_id
     * @param $limit
     * @return array
     */
    protected function getSeedVote($match_id, $limit = '')
    {
        if ($limit !== '') {
            $res = M('vote')->field('seed_id, count(seed_id) as vote_num')
                            ->where(array('match_id' => $match_id))
                            ->group('seed_id')
                            ->order("count(seed_id) desc")
                            ->limit($limit)
                            ->select();
        } else {
            $res = M('vote')->field('seed_id, count(seed_id) as vote_num')
                            ->where(array('match_id' => $match_id))
                            ->group('seed_id')
                            ->order("count(seed_id) desc")
                            ->select();
        }

        $list = array();
        if ($res) {
            // 获取所有种子选手信息
            foreach($res as $k => $v) {
                $seed = M('seed')->where(array('id' => $v['seed_id']))->find();
                $list[$k]['vote_num'] = $v['vote_num'];
                $list[$k]['id'] = $seed['id'];
                $list[$k]['name'] = $seed['name'];
                $list[$k]['phone'] = $seed['phone'];
                $list[$k]['photo_url'] = $seed['photo_url'];
                $list[$k]['introduce'] = $seed['introduce'];
            }
        }
        return $list;
    }

    /**
     * 获取用户头像信息
     *
     * @param $uid
     * @return string
     */
    protected function getUserImg($uid)
    {
        $path = $this->get_avatar($uid);
        $name = $this->get_avatarName($uid);
        $file_path = HEAD_ROOT . '/Uploads/Api/user/' . $path . $name . '.jpg';
        if (file_exists($file_path)) {
            $file_path = C('IMG_URL') . '/Uploads/Api/user/' . $path . $name . '.jpg';
        } else {
            $file_path = C('IMG_URL') . '/Uploads/Api/user/defaultUserImage.png';
        }
        return $file_path;
    }

    /**
     * 用户头像存储取出文件夹地址
     *
     * @param $uid
     * @return string
     */
    protected function get_avatar($uid)
    {
        $uid = abs(intval($uid));
        $uid = sprintf("%09d", $uid);
        $dir1 = substr($uid, 0, 3);
        $dir2 = substr($uid, 3, 2);
        $dir3 = substr($uid, 5, 2);
        return $dir1 . '/' . $dir2 . '/' . $dir3 . '/';
    }

    /**
     * 生成文件夹
     *
     * @param $uid
     * @param $folder
     * @return string
     */
    protected function generalFolder($uid, $folder)
    {
        $uid  = abs(intval($uid));
        $uid  = sprintf("%09d", $uid);
        $dir1 = substr($uid, 0, 3);
        $dir2 = substr($uid, 3, 2);
        $dir3 = substr($uid, 5, 2);
        $dir4 = substr($uid, 7, 2);

        return '/' . $folder . '/' . $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . $dir4 . '/';
    }

    /**
     * 用户头像存储取出文件名
     *
     * @param $uid
     * @return number|string
     */
    protected function get_avatarName($uid)
    {
        $uid = abs(intval($uid));
        $uid = sprintf("%09d", $uid);
        $uid = substr($uid, -2);
        return $uid;
    }

    /**
     * 下载头像
     *
     * @param $file_url
     * @param $save_to
     * @param $id
     */
    protected function download_remote_file($file_url, $save_to, $id)
    {
        // 获取位置
        $hearurl = $this->get_avatar($id);
        // 拼出据对路径
        $url = HEAD_ROOT . '/Uploads/Api/user/' . $hearurl;
        // 查询是否由此路径没有则创建
        createFolders($url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_URL, $file_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $file_content = curl_exec($ch);
        curl_close($ch);
        $downloaded_file = fopen($save_to, 'w');
        fwrite($downloaded_file, $file_content);
        fclose($downloaded_file);

        return $save_to;
    }

    /**
     * 上传头像
     *
     * @param        $id
     * @param        $name 是上传图片的name属性
     * @param        $data 图片数据
     * @param        $prefix 前缀
     * @param null   $old_path
     * @param bool   $is_thumb
     * @param string $thumb_width
     * @param string $thumb_height
     *
     * @return string
     */
    protected function upLoadImage($id, $name, $data, $prefix, $old_path = null, $is_thumb = false, $thumb_width = '', $thumb_height = '')
    {
        if (!$id || !$name || !$data) {
            return false;
        }
        $upload           = new \Think\Upload();   // 实例化上传类
        $upload->maxSize  = C('SYS_UPLOAD.LIMIT');      // 设置附件上传大小
        $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->thumb    = true;
        $upload_path      = HEAD_ROOT . '/Uploads/';  // 两边的斜杠不能少
        $upload->subName  = '';
        $upload->rootPath = $upload_path;
        $upload->saveRule = 'uniqid';
        $upload->savePath = $this->generalFolder($id, $name);

        // 如果有图，删除原来的
        if ($old_path !== null) {
            $unLink = HEAD_ROOT . $old_path;
            $del_flg = unlink($unLink);
            if (!$del_flg) {
                return false;
            }
        }
        // 上传文件
        $info = $upload->upload($data);

        if (!$info) {
            return $upload->getError();
        }
        if (empty($thumb_width)) {
            $thumb_width = C('SYS_UPLOAD_IMAGE.THUMB_WIDTH');
        }
        if (empty($thumb_height)) {
            $thumb_height = C('SYS_UPLOAD_IMAGE.THUMB_HEIGHT');
        }

        // 缩略图处理
        if ($is_thumb) {
            $image = new \Think\Image();
            $kenamey = $info[$name]['kenamey'];
            $imageFile      = $upload_path . $info[$kenamey]['savepath'] . $info[$kenamey]['savename'];
            $thumbImageFile = $upload_path . $info[$kenamey]['savepath'] . $prefix . $info[$kenamey]['savename'];

            $image->open($imageFile)
                ->thumb($thumb_width, $thumb_height, \Think\Image::IMAGE_THUMB_CENTER)
                ->save($thumbImageFile);

            $path = '/Uploads' . $info[$kenamey]['savepath'] . $prefix . $info[$kenamey]['savename'];
            @unlink($imageFile);
        } else {
            $path = '/Uploads' . $info[$name]['savepath'] . $info[$name]['savename'];
        }
        return $path;
    }
}